<template>
  <div class="comment-management">
    <a-card title="农产品评论管理" :bordered="false" class="main-card">
      <template #extra>
        <a-space>
          <a-input-search
            placeholder="输入关键词搜索评论"
            style="width: 300px"
            allow-clear
            @search="handleSearch"
          />
        </a-space>
      </template>

      <a-spin :loading="loading">
        <a-row :gutter="24" class="product-grid">
          <a-col
            v-for="product in productList"
            :key="product.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="6"
          >
            <a-card class="product-card">
              <div class="product-header">
                <a-image
                  :src="product.coverImage"
                  :width="120"
                  :height="120"
                  class="product-image"
                  :preview="false"
                  :show-loader="true"
                >
                  <template #error>
                    <div class="image-error">
                      <icon-image width="40" height="40" />
                    </div>
                  </template>
                </a-image>
                <a-tag class="product-tag" color="arcoblue" size="large">
                  {{ product.title }}
                </a-tag>
              </div>

              <a-divider class="custom-divider" />

              <div class="comment-container">
                <div v-if="product.comments.length" class="comment-list">
                  <a-scrollbar
                    outer-class="comment-scrollbar"
                    :style="{ height: commentScrollHeight }"
                  >
                    <div
                      v-for="comment in product.comments"
                      :key="comment.commentId"
                      class="comment-item"
                    >
                      <div class="comment-content">
                        <a-space align="start">
                          <a-avatar
                            :size="32"
                            :style="{
                              backgroundColor: stringToColor(comment.userId),
                            }"
                          >
                            {{ comment.userId.slice(-2) }}
                          </a-avatar>
                          <div class="comment-body">
                            <div class="comment-meta">
                              <span class="user-id"
                                >用户{{ comment.userId }}</span
                              >
                              <span class="comment-time">
                                {{ formatTimeAgo(comment.createTime) }}
                              </span>
                            </div>
                            <div class="comment-text">
                              {{ comment.content }}
                            </div>
                          </div>
                        </a-space>
                      </div>
                      <a-popconfirm
                        content="确定要删除这条评论吗？"
                        position="br"
                        @ok="handleDeleteComment(product.id, comment.commentId)"
                      >
                        <a-button
                          type="text"
                          shape="circle"
                          status="danger"
                          class="delete-btn"
                        >
                          <template #icon>
                            <icon-delete />
                          </template>
                        </a-button>
                      </a-popconfirm>
                    </div>
                  </a-scrollbar>
                </div>
                <div v-else class="empty-comments">
                  <a-empty description="暂无评论" />
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-spin>

      <div class="pagination-wrapper">
        <a-pagination
          :total="total"
          :page-size="pageSize"
          show-total
          show-jumper
          show-page-size
          @change="handlePageChange"
        />
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import { IconDelete } from "@arco-design/web-vue/es/icon";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { CommentControllerService } from "@/generated"; // 导入 relativeTime 插件

// 使用 relativeTime 插件
dayjs.extend(relativeTime);

// 模拟数据
const productList = ref([]);

// 分页相关
const total = ref(0);
const pageSize = ref(8);
const loading = ref(false);

// 获取所有商品评论
const getAllProductComments = async (pageNumber = 1, pageSize = 8, value) => {
  try {
    loading.value = true;
    const res = await CommentControllerService.getProductWithCommentsPage({
      pageNumber: pageNumber,
      pageSize: pageSize,
      searchText: value,
    });
    if (res.code === 0) {
      productList.value = res.data.records.map((product) => ({
        ...product,
        comments: product.comments.map((comment) => ({
          ...comment,
          createTime: dayjs(comment.createTime).format("YYYY-MM-DD HH:mm:ss"),
        })),
      }));
      total.value = res.data.total;
      loading.value = false;
      console.log("获取商品评论成功:", productList.value);
    }
  } catch (error) {
    console.error("获取商品评论失败:", error);
  }
};

// 时间格式化
const formatTimeAgo = (time) => {
  return dayjs(time).fromNow();
};

// 删除评论
const handleDeleteComment = (productId, commentId) => {
  CommentControllerService.deleteComment({
    commentId: commentId,
  }).then((res) => {
    console.log("删除评论:", res);
    if (res.code === 0) {
      Message.success("删除评论成功");
      getAllProductComments();
    }
  });
};

// 搜索处理
const handleSearch = (value) => {
  console.log("执行搜索:", value);
  // 设置value的默认值为空字符串
  value = value || "";
  getAllProductComments(1, pageSize.value, value);
};

// 分页处理
const handlePageChange = (page) => {
  console.log("切换页码:", page);
  getAllProductComments(page, pageSize.value);
};

// 页面初始化，函数
onMounted(getAllProductComments);

// ...原有脚本部分保持不变，新增颜色生成函数...
const stringToColor = (str) => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  const hue = Math.abs(hash % 360);
  return `hsl(${hue}, 70%, 50%)`;
};
</script>

<style scoped>
.comment-management {
  padding: 24px;
  background: #f5f6f7;
}

.main-card {
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.product-grid {
  margin: -12px;
}

.product-card {
  height: 100%;
  margin: 12px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.product-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-4px);
}

.product-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.product-image {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

.product-tag {
  width: 100%;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  padding: 8px 12px;
  border-radius: 6px;
}

.custom-divider {
  margin: 12px 0;
  border-color: var(--color-border-2);
}

.comment-container {
  height: 300px; /* 固定高度 */
  padding: 0 8px;
}

.comment-scrollbar {
  max-height: 280px; /* 略小于容器高度 */
}

.comment-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px;
  margin-bottom: 8px;
  background: var(--color-bg-2);
  border-radius: 8px;
  transition: background 0.2s;
}

.comment-item:hover {
  background: var(--color-bg-3);
}

.comment-body {
  flex: 1;
  margin-left: 12px;
}

.comment-meta {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 4px;
}

.user-id {
  font-size: 13px;
  font-weight: 500;
  color: var(--color-text-1);
}

.comment-time {
  font-size: 12px;
  color: var(--color-text-3);
}

.comment-text {
  font-size: 14px;
  color: var(--color-text-2);
  line-height: 1.5;
  word-break: break-word;
}

.delete-btn {
  flex-shrink: 0;
  margin-left: 12px;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: var(--color-fill-2);
  color: var(--color-text-3);
}

.empty-comments {
  padding: 24px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .product-card {
    margin: 8px;
  }

  .product-image {
    width: 80px;
    height: 80px;
  }

  .product-tag {
    font-size: 14px;
  }

  .comment-container {
    height: 250px;
  }

  .comment-scrollbar {
    max-height: 230px;
  }
}
</style>
